package com.example.dicegame.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
@Service
public class RedisService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    public void setString(String key,String value){
        redisTemplate.opsForValue().set(key,value);
    }
    public void setStringWithExpire(String key,String value, long timeout, TimeUnit unit){

        redisTemplate.opsForValue().set(key,value,timeout,unit);
    }
    public String getString(String key){
        return (String) redisTemplate.opsForValue().get(key);
    }
    public Long increment(String key){
        return redisTemplate.opsForValue().increment(key);
    }
    //=======Hash================

    public void setHash(String key ,String field,Object value) {
        redisTemplate.opsForHash().put(key,field,value);
    }

    public Object getHash(String key ,String field){
        return redisTemplate.opsForHash().get(key,field);
    }
    public Object getHashAll(String key){
        return redisTemplate.opsForHash().entries(key);
    }
    //======set======
    public Long addToSet(String key,Object value){
        return  redisTemplate.opsForSet().add(key,value);
    }
    public Object getSetAll(String key){
        return redisTemplate.opsForSet().members(key);
    }
    public Boolean isMembersOfSet(String key,Object value){
        return redisTemplate.opsForSet().isMember(key,value);
    }
    public Long getSetSize(String key){
        return redisTemplate.opsForSet().size(key);
    }
    public Boolean delete(String key){
        return redisTemplate.delete(key);
    }
    public Boolean hasKey(String key){
        return redisTemplate.hasKey(key);
    }
    public Boolean expire(String key,Long timeout,TimeUnit unit){
        return redisTemplate.expire(key,timeout,unit);
    }
    // ==================== List 操作 ====================

    /**
     * 向左添加元素到列表
     */
    public Long leftPush(String key, Object value) {
        return redisTemplate.opsForList().leftPush(key, value);
    }

    /**
     * 获取列表范围元素
     */
    public List<Object> range(String key, long start, long end) {
        return redisTemplate.opsForList().range(key, start, end);
    }

    /**
     * 获取列表大小
     */
    public Long listSize(String key) {
        return redisTemplate.opsForList().size(key);
    }

    /**
     * 修剪列表
     */
    public void listTrim(String key, long start, long end) {
        redisTemplate.opsForList().trim(key, start, end);
    }
}
